//
//  ZMYReadPageViewController.m
//  QiYReader
//
//  Created by 奇阅科技 on 14/12/5.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "ZMYReadPageViewController.h"
#import "Config.h"
#import "ReadConfig.h"
#import "UMSocial.h"
@interface ZMYReadPageViewController ()<UITextViewDelegate,ReadTextViewDelegate,UMSocialUIDelegate>

@end

@implementation ZMYReadPageViewController
-(void)dealloc{
    NSLog(@"仿真翻页释放了");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [ReadConfig currentAccount].bgColor;
    if (self.textObject!=nil) {
        [self setTextHighlighted];
    }
    self.textView.readDelegate = self;
    self.titleNameLabel.text = self.bookChapterInfo.chapterName;
    self.titleNameLabel.textColor = [ReadConfig currentAccount].titleColor;
    CGFloat percent = (CGFloat)self.indexItem/self.allItemNum;
    self.percentageLabel.text = [NSString stringWithFormat:@"%.1f%%",percent*100];
    self.percentageLabel.textColor = [ReadConfig currentAccount].titleColor;
    
    self.textView.tintColor = RGB_COLOR(116, 178, 77);
    UIMenuItem *menuItem2 = [[UIMenuItem alloc]initWithTitle:@"高亮" action:@selector(highlighted)];
    UIMenuItem *menuItem22 = [[UIMenuItem alloc]initWithTitle:@"取消高亮" action:@selector(cancelHighlighted)];
//    UIMenuItem *menuItem3 = [[UIMenuItem alloc]initWithTitle:@"笔记" action:@selector(bookNote)];
//    UIMenuItem *menuItem33 = [[UIMenuItem alloc]initWithTitle:@"删除笔记" action:@selector(deleteBookNote)];
    UIMenuItem *menuItem4 = [[UIMenuItem alloc]initWithTitle:@"分享" action:@selector(shareText)];
    UIMenuController *menu = [UIMenuController sharedMenuController];
    menu.menuItems = @[menuItem2,menuItem22,menuItem4];
    [menu setMenuVisible:YES animated:YES];
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(highlighted) || action == @selector(cancelHighlighted)) {
        NSRange selectedRange = self.textView.selectedRange;//当前选择的文字在本页面的位置
        BookChapterText *chapterText = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.readSchedule.articleid chapterId:self.readSchedule.chapterId];
        NSRange currentRange = [chapterText.chapterTextString rangeOfString:self.textObject];//当前页面的所有文字在本章节的位置
        NSRange currentselectedRange = NSMakeRange(currentRange.location+selectedRange.location,selectedRange.length);//当前选择的文字在本章节的位置
        NSArray *highlightMarks = [[ZMYLKDB getLKDBHelper]getHighlightMarkChapterId:self.bookChapterInfo.chapterId];
        BOOL isHighlightMark = NO;
        for (HighlightMark *highlightMark in highlightMarks) {
            NSRange mrang = NSIntersectionRange(NSRangeFromString(highlightMark.rang), currentselectedRange);
            if (mrang.length>0) {
                isHighlightMark = YES;
                 NSRange currentHighlightRange = NSIntersectionRange(NSRangeFromString(highlightMark.rang), currentRange);//当前高亮的文字在本章节中本页的位置
                self.textView.selectedRange = NSMakeRange(currentHighlightRange.location-currentRange.location,currentHighlightRange.length);//当前高亮的文字在本页的位置
                break;
            }
        }
        if (action == @selector(highlighted)) {
            return !isHighlightMark;
        }else{
            return isHighlightMark;
        }
    }else if (action == @selector(bookNote) || action == @selector(deleteBookNote)) {
        NSRange selectedRange = self.textView.selectedRange;//当前选择的文字在本页面的位置
        BookChapterText *chapterText = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.readSchedule.articleid chapterId:self.readSchedule.chapterId];
        NSRange currentRange = [chapterText.chapterTextString rangeOfString:self.textObject];//当前页面的所有文字在本章节的位置
        NSRange currentselectedRange = NSMakeRange(currentRange.location+selectedRange.location,selectedRange.length);//当前选择的文字在本章节的位置
        NSArray *highlightMarks = [[ZMYLKDB getLKDBHelper]getBookNoteChapterId:self.bookChapterInfo.chapterId];
        BOOL isHighlightMark = NO;
        for (BookNote *highlightMark in highlightMarks) {
            NSRange mrang = NSIntersectionRange(NSRangeFromString(highlightMark.rang), currentselectedRange);
            if (mrang.length>0) {
                isHighlightMark = YES;
                NSRange currentHighlightRange = NSIntersectionRange(NSRangeFromString(highlightMark.rang), currentRange);//当前高亮的文字在本章节中本页的位置
                self.textView.selectedRange = NSMakeRange(currentHighlightRange.location-currentRange.location,currentHighlightRange.length);//当前高亮的文字在本页的位置
                break;
            }
        }
        if (action == @selector(highlighted)) {
            return !isHighlightMark;
        }else{
            return isHighlightMark;
        }
    }else if (action == @selector(shareText)) {
        return YES;
    }else{
        return NO;
    }
}
#pragma mark 添加高亮
-(void)highlighted{
    NSRange selectedRange = self.textView.selectedRange;
    BookChapterText *chapterText = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.readSchedule.articleid chapterId:self.readSchedule.chapterId];
    NSRange currentRange = [chapterText.chapterTextString rangeOfString:self.textObject];
    NSRange currentselectedRange = NSMakeRange(currentRange.location+selectedRange.location,selectedRange.length);
    HighlightMark *highlightMark = [HighlightMark new];
    highlightMark.articleid = self.readSchedule.articleid;
    highlightMark.chapterId = self.readSchedule.chapterId;
    highlightMark.rang = NSStringFromRange(currentselectedRange);
    highlightMark.textString = [chapterText.chapterTextString substringWithRange:currentselectedRange];
    [[ZMYLKDB getLKDBHelper]insertToHighlightMarkDB:highlightMark];
    [self setTextHighlighted];
}
#pragma mark 取消高亮
-(void)cancelHighlighted{
    NSRange selectedRange = self.textView.selectedRange;
    BookChapterText *chapterText = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.readSchedule.articleid chapterId:self.readSchedule.chapterId];
    NSRange currentRange = [chapterText.chapterTextString rangeOfString:self.textObject];
    NSRange currentselectedRange = NSMakeRange(currentRange.location+selectedRange.location,selectedRange.length);
    NSArray *highlightMarks = [[ZMYLKDB getLKDBHelper]getHighlightMarkChapterId:self.bookChapterInfo.chapterId];
    for (HighlightMark *highlightMark in highlightMarks) {
        NSRange mrang = NSIntersectionRange(NSRangeFromString(highlightMark.rang), currentselectedRange);
        if (mrang.length>0) {
            [[ZMYLKDB getLKDBHelper]deleteToHighlightMarkDB:highlightMark];
            break;
        }
    }
    [self setTextHighlighted];
}
#pragma mark 添加笔记
-(void)bookNote{
    NSRange selectedRange = self.textView.selectedRange;
    BookChapterText *chapterText = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.readSchedule.articleid chapterId:self.readSchedule.chapterId];
    NSRange currentRange = [chapterText.chapterTextString rangeOfString:self.textObject];
    NSRange currentselectedRange = NSMakeRange(currentRange.location+selectedRange.location,selectedRange.length);
    BookNote *highlightMark = [BookNote new];
    highlightMark.articleid = self.readSchedule.articleid;
    highlightMark.chapterId = self.readSchedule.chapterId;
    highlightMark.rang = NSStringFromRange(currentselectedRange);
    [[ZMYLKDB getLKDBHelper]insertToBookNoteDB:highlightMark];
    [self setTextHighlighted];
}
#pragma mark 删除笔记
-(void)deleteBookNote{
    NSRange selectedRange = self.textView.selectedRange;
    BookChapterText *chapterText = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.readSchedule.articleid chapterId:self.readSchedule.chapterId];
    NSRange currentRange = [chapterText.chapterTextString rangeOfString:self.textObject];
    NSRange currentselectedRange = NSMakeRange(currentRange.location+selectedRange.location,selectedRange.length);
    NSArray *highlightMarks = [[ZMYLKDB getLKDBHelper]getHighlightMarkChapterId:self.bookChapterInfo.chapterId];
    for (HighlightMark *highlightMark in highlightMarks) {
        NSRange mrang = NSIntersectionRange(NSRangeFromString(highlightMark.rang), currentselectedRange);
        if (mrang.length>0) {
            [[ZMYLKDB getLKDBHelper]deleteToHighlightMarkDB:highlightMark];
            break;
        }
    }
    [self setTextHighlighted];
}
#pragma mark 分享文字
-(void)shareText{
    NSRange selectedRange = self.textView.selectedRange;
    NSString *selectedStr = [self.textObject substringWithRange:selectedRange];
    if (selectedStr.length>120) {
        [AppDelegate showHUDAndHide:@"分享内容过长，请修改后重新分享" view:[AppDelegate delegate].window];
        return;
    }
    [UMSocialSnsService presentSnsIconSheetView:self appKey:nil shareText:selectedStr shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone,UMShareToDouban,UMShareToRenren,UMShareToSms,nil] delegate:self];
    UMSocialUrlResource *urlResource = [[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeImage url:self.book.imagefname];
    [UMSocialData defaultData].extConfig.sinaData.shareText = [NSString stringWithFormat:@"《%@》%@http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.title,selectedStr,self.book.articleid];
    [UMSocialData defaultData].extConfig.sinaData.urlResource = urlResource;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = [NSString stringWithFormat:@"http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.articleid];
    [UMSocialData defaultData].extConfig.wechatSessionData.title = [NSString stringWithFormat:@"《%@》",self.book.title];
    [UMSocialData defaultData].extConfig.wechatSessionData.urlResource = urlResource;
    
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = [NSString stringWithFormat:@"http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.articleid];
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = [NSString stringWithFormat:@"《%@》%@",self.book.title,selectedStr];
    [UMSocialData defaultData].extConfig.wechatTimelineData.urlResource = urlResource;
    
    [UMSocialData defaultData].extConfig.qqData.url = [NSString stringWithFormat:@"http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.articleid];
    [UMSocialData defaultData].extConfig.qqData.title = [NSString stringWithFormat:@"《%@》",self.book.title];
    [UMSocialData defaultData].extConfig.qqData.urlResource = urlResource;
    [UMSocialData defaultData].extConfig.qzoneData.url = [NSString stringWithFormat:@"http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.articleid];
    [UMSocialData defaultData].extConfig.qzoneData.title = [NSString stringWithFormat:@"《%@》",self.book.title];
    [UMSocialData defaultData].extConfig.qzoneData.urlResource = urlResource;
    
    [UMSocialData defaultData].extConfig.doubanData.shareText = [NSString stringWithFormat:@"《%@》%@http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.title,selectedStr,self.book.articleid];
    [UMSocialData defaultData].extConfig.renrenData.shareText = [NSString stringWithFormat:@"《%@》%@http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.title,selectedStr,self.book.articleid];
    [UMSocialData defaultData].extConfig.smsData.shareText = [NSString stringWithFormat:@"《%@》%@http://dataapi.yuewen.cc/web/store.php?a=fenxiang&bookid=%@",self.book.title,selectedStr,self.book.articleid];
}
-(BOOL)isDirectShareInIconActionSheet
{
    return YES;
}
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
//        [AppDelegate showHUDAndHide:[NSString stringWithFormat:@"分享到%@成功！",[[response.data allKeys] objectAtIndex:0]] view:self.view];
        [AppDelegate showHUDAndHide:@"分享到成功！" view:self.view];
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}
#pragma mark 刷新页面的高亮文字
- (void)setTextHighlighted{
    NSArray *highlightMarks = [[ZMYLKDB getLKDBHelper]getHighlightMarkChapterId:self.bookChapterInfo.chapterId];
    BookChapterText *chapterText = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.readSchedule.articleid chapterId:self.readSchedule.chapterId];
    NSRange currentRange = [chapterText.chapterTextString rangeOfString:self.textObject];
    NSMutableAttributedString *attributedText = [self getStringAttributed];
    for (HighlightMark *highlightMark in highlightMarks) {
        NSRange mrang = NSIntersectionRange(NSRangeFromString(highlightMark.rang), currentRange);
        if (mrang.length>0) {
//            [attributedText addAttributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleThick), NSForegroundColorAttributeName: RGB_COLOR(116, 178, 77) } range:NSMakeRange(mrang.location-currentRange.location,mrang.length)];
//            [attributedText addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleThick] range:NSMakeRange(mrang.location-currentRange.location,mrang.length)];
            [attributedText addAttribute:NSForegroundColorAttributeName value:RGB_COLOR(116, 178, 77) range:NSMakeRange(mrang.location-currentRange.location,mrang.length)];
//            [attributedText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:16] range:NSMakeRange(mrang.location-currentRange.location,20)];
//            [attributedText addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:-3] range:NSMakeRange(mrang.location-currentRange.location,mrang.length)];
//            [attributedText addAttribute:NSUnderlineColorAttributeName value:RGB_COLOR(116, 178, 77) range:NSMakeRange(mrang.location-currentRange.location,mrang.length)];
        }
    }
    [self.textView setAttributedText:attributedText];
}
-(void)changeColor{
    self.view.backgroundColor = [ReadConfig currentAccount].bgColor;
    [self setTextHighlighted];
    self.titleNameLabel.text = self.bookChapterInfo.chapterName;
    self.titleNameLabel.textColor = [ReadConfig currentAccount].titleColor;
    CGFloat percent = (CGFloat)self.indexItem/self.allItemNum;
    self.percentageLabel.text = [NSString stringWithFormat:@"%.1f%%",percent*100];
    self.percentageLabel.textColor = [ReadConfig currentAccount].titleColor;
}

-(NSMutableAttributedString *)getStringAttributed{
    if (self.textObject==nil) {
        return nil;
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineHeightMultiple  = 1.3f;                    // 可变行高,乘因数
    paragraphStyle.lineSpacing         = 1.0f;                    // 行间距
    paragraphStyle.paragraphSpacing    = 1.0f;                   // 段间距
    paragraphStyle.alignment           = NSTextAlignmentLeft;    // 对齐方式
    paragraphStyle.tailIndent          = SCREEN_WIDTH-30;                    // 文本宽度
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    NSTextStorage *text = [[NSTextStorage alloc]initWithString:self.textObject];
    [text addAttribute:NSParagraphStyleAttributeName
                 value:paragraphStyle
                 range:NSMakeRange(0, text.length)];
    // 字体属性
    [text addAttribute:NSFontAttributeName
                 value:[UIFont systemFontOfSize:[ReadConfig currentAccount].foutSize]
                 range:NSMakeRange(0, text.length)];
    
    [text addAttribute:NSForegroundColorAttributeName
                 value:[ReadConfig currentAccount].textColor
                 range:NSMakeRange(0, text.length)];
    return text;
}

-(void)changeTextView{
    // 文本容器
    NSTextStorage *storage = [[NSTextStorage alloc] initWithString:self.textObject];
    // 文本容器的布局管理器
    NSLayoutManager *layoutManager = [NSLayoutManager new];
    [storage addLayoutManager:layoutManager];
    // 段落属性
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineHeightMultiple  = 1.3f;                    // 可变行高,乘因数
    paragraphStyle.lineSpacing         = 1.0f;                    // 行间距
    paragraphStyle.paragraphSpacing    = 1.0f;                   // 段间距
    paragraphStyle.alignment           = NSTextAlignmentLeft;    // 对齐方式
    paragraphStyle.tailIndent          = SCREEN_WIDTH-30;                    // 文本宽度
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    [storage addAttribute:NSParagraphStyleAttributeName
                    value:paragraphStyle
                    range:NSMakeRange(0, storage.string.length)];
    // 字体属性
    [storage addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:[ReadConfig currentAccount].foutSize]
                    range:NSMakeRange(0, storage.string.length)];
    
    [storage addAttribute:NSForegroundColorAttributeName
                    value:[ReadConfig currentAccount].textColor
                    range:NSMakeRange(0, storage.string.length)];
    // 分段显示文本容器中的内容
    CGSize textFrame = CGSizeMake(SCREEN_WIDTH-30, SCREEN_HEIGHT-80);
    NSTextContainer *textContainer1 = [[NSTextContainer alloc] initWithSize:textFrame];
    [layoutManager addTextContainer:textContainer1];
    UITextViewAdditions *textView = [[UITextViewAdditions alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-30, SCREEN_HEIGHT-63) textContainer:textContainer1];
    textView.backgroundColor = [UIColor clearColor];
    textView.editable = NO;
    textView.readDelegate = self;
    [self.textView removeFromSuperview];
    self.textView = textView;
    [self.textBgView addSubview:self.textView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
